# 思和智库 - Windows 自动化部署脚本
# PowerShell 版本

$ErrorActionPreference = "Stop"

Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "思和智库 - 自动化部署脚本 (Windows)" -ForegroundColor Cyan
Write-Host "==========================================" -ForegroundColor Cyan

# 项目路径（根据实际情况修改）
$ProjectDir = "D:\AUG\sihe-think-tank"
$BackendDir = Join-Path $ProjectDir "backend"
$FrontendDir = Join-Path $ProjectDir "frontend"

# 备份目录
$BackupDir = Join-Path $ProjectDir "backups"
$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"

try {
    Write-Host "`n步骤 1/7: 检查环境..." -ForegroundColor Yellow
    
    # 检查必要的命令
    $commands = @("git", "python", "node", "npm")
    foreach ($cmd in $commands) {
        if (-not (Get-Command $cmd -ErrorAction SilentlyContinue)) {
            throw "$cmd 未安装或不在 PATH 中"
        }
    }
    Write-Host "✅ 环境检查通过" -ForegroundColor Green

    Write-Host "`n步骤 2/7: 创建备份..." -ForegroundColor Yellow
    New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null
    
    $DataDir = Join-Path $BackendDir "data"
    if (Test-Path $DataDir) {
        $BackupFile = Join-Path $BackupDir "data_$Timestamp.zip"
        Compress-Archive -Path $DataDir -DestinationPath $BackupFile -Force
        Write-Host "✅ 数据备份完成: $BackupFile" -ForegroundColor Green
    }

    Write-Host "`n步骤 3/7: 拉取最新代码..." -ForegroundColor Yellow
    Set-Location $ProjectDir
    git stash
    git pull origin master
    Write-Host "✅ 代码更新完成" -ForegroundColor Green

    Write-Host "`n步骤 4/7: 更新后端依赖..." -ForegroundColor Yellow
    Set-Location $BackendDir
    & ".\venv\Scripts\Activate.ps1"
    pip install -r requirements.txt --quiet
    Write-Host "✅ 后端依赖更新完成" -ForegroundColor Green

    Write-Host "`n步骤 5/7: 运行后端测试..." -ForegroundColor Yellow
    $testResult = python run_tests.py
    if ($LASTEXITCODE -ne 0) {
        throw "后端测试失败！部署中止。"
    }
    Write-Host "✅ 后端测试通过" -ForegroundColor Green

    Write-Host "`n步骤 6/7: 更新前端..." -ForegroundColor Yellow
    Set-Location $FrontendDir
    npm install --silent
    npm run build
    Write-Host "✅ 前端构建完成" -ForegroundColor Green

    Write-Host "`n步骤 7/7: 重启服务..." -ForegroundColor Yellow
    Write-Host "⚠️  请手动重启前后端服务" -ForegroundColor Yellow
    Write-Host "   后端: 在 $BackendDir 运行 'python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 3301'" -ForegroundColor White
    Write-Host "   前端: 在 $FrontendDir 运行 'npm run dev'" -ForegroundColor White

    Write-Host "`n==========================================" -ForegroundColor Cyan
    Write-Host "🎉 部署完成！" -ForegroundColor Green
    Write-Host "==========================================" -ForegroundColor Cyan
    Write-Host "后端服务: http://localhost:3301"
    Write-Host "前端服务: http://localhost:3000"
    Write-Host "备份位置: $BackupDir\data_$Timestamp.zip"

} catch {
    Write-Host "`n❌ 部署失败: $_" -ForegroundColor Red
    exit 1
}

